const fs = require('fs');
const path = require('path');
const _ = require('lodash');  
const { v4: uuidv4 } = require('uuid');  
const { format } = require("date-fns");
const { configFilePath,configdirName } = require('../appConfig');

// 检查文件夹是否存在如果不存在则新建文件夹 递归创建
async function createDirectoryRecursive(directoryPath) {  
    try {  
      if (!fs.existsSync(directoryPath)) {  
        const parentDir = path.dirname(directoryPath);  
        await createDirectoryRecursive(parentDir);  
        fs.mkdirSync(directoryPath, { recursive: true });  
      }  
    } catch (error) {  
      console.error(`Error creating directory: ${error}`);  
    }  
  }

// 指定上传文件的目录
const SetFilePath = async (dir) => {
    if (!fs.existsSync(dir)) {
       await createDirectoryRecursive(dir)
    }
    return dir;
}

//单-多 文件上传公共处理
const FilePath = async (files) => {
    let _temp = [];
    if(_.isArray(files)){
        _temp = files;
    }else{
        _temp.push(files)
    }
    const p =  new Promise((resolve, rejected) => {
      let list = [];
      _temp.forEach(async (file) => {
          let fileObj = {};
          let _attribute = ['size','mimetype','originalFilename'];
          _attribute.forEach((attr) => {
              if(!fileObj[attr]){
                fileObj[attr] = file[attr];
              }
          })
          const reader = fs.createReadStream(file.filepath);
          fileObj.ext = file.originalFilename.split('.').pop();
          fileObj.fileName = `${Date.now()}.${fileObj.ext}`;
          const dirName = format(new Date(),configdirName);
          const dir = path.join(__dirname, `..${configFilePath + dirName}`);
          await SetFilePath(dir);
          let newFilePath = `${dir + '/' + fileObj.fileName}`
          const stream = fs.createWriteStream(newFilePath);
          fileObj.path = `${"/upload/" + dirName + "/" +fileObj.fileName}`;
          fileObj.uuid = uuidv4()
          reader.pipe(stream);
          list.push(fileObj);
      })
      resolve(list)
    })
    return await p;
}
module.exports = {
    FilePath: FilePath
  }